package com.it.security.config;

import com.it.security.service.MyUserDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
@Slf4j
@EnableGlobalMethodSecurity(prePostEnabled = true) //使用注解方式权限控制  在controller 或service中的方法上使用注解进行权限控制
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    MyUserDetailsService myUserDetailsService;

    @Autowired
    CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
    // 定制请求的授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable().authorizeRequests()
                .antMatchers("/test").hasAnyAuthority("1") //表示需要 1 权限才能访问
                .antMatchers("/level2/**").hasAnyRole("VIP2")   // 表示需要VIP2 角色才能访问
                .antMatchers("/level3/**").hasAnyRole("VIP3")   // 表示需要VIP3 角色才能访问
                .antMatchers("/security").hasAnyAuthority("1") //表示需要 2 权限才能访问
                .antMatchers("/**").authenticated();  //请求 /  路径下都需要认证才能放行
                //.anyRequest().permitAll(); // 其它url完全开发
        http.formLogin()
                .loginProcessingUrl("/login")  //指定我们自己的登录页,spring security以重定向方式跳转到/login-view
//                .successHandler()  //自定义认证成功处理器
                .failureHandler(customAuthenticationFailureHandler) //自定义认证失败处理器
                .defaultSuccessUrl("/success");
        // 开启自动配置的注销功能，会访问logout请求
        http.logout().logoutSuccessUrl("/"); //注销成功后，回到首页





    }

    //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //使用自定认证规则,并且使用BCrypt算法处理密码
        auth.userDetailsService(myUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());

    }

}
